package com.yinhe.music.yhmusic.db.dao;

import com.hwangjr.rxbus.RxBus;
import com.j256.ormlite.dao.Dao;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusListObject;
import com.yinhe.music.yhmusic.db.AbstractBaseDb;
import com.yinhe.music.yhmusic.db.DbHelper;
import com.yinhe.music.yhmusic.db.bean.RecentMusicDBEntity;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by wangyang on 17/3/18.
 */

public class RecentSongEntityDAO extends AbstractBaseDb {

    private static final String TAG = RecentSongEntityDAO.class.getSimpleName();
    private Dao dao;


    public RecentSongEntityDAO(DbHelper dbHelper) {
        super(dbHelper);
        dao = getDao(RecentMusicDBEntity.class);
    }


    public void insertSongSyn(final RecentMusicDBEntity recentEntity) {
        try {
            dao.createOrUpdate(recentEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public boolean updateSong(final RecentMusicDBEntity recentEntity) {
        try {
            dao.update(recentEntity);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public List<RecentMusicDBEntity> getAllRecent() {
        try {
            List<RecentMusicDBEntity> info = (List<RecentMusicDBEntity>) dao.queryBuilder().
                    orderBy(RecentMusicDBEntity.RecentSongColums.TIME, false).query();
            return info;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public long getRecentCount() {
        try {
            return dao.queryBuilder().countOf();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    public void deleteSongListByIdList(final List<Integer> idList) {
        try {
            for (Integer i : idList) {
                dao.deleteById(i);
            }
            RxBus.get().post(RxBusEventType.Recent.DELETE_RECENT_MUSIC, RxbusListObject.instance(idList));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteRecentSong(long id) {
        try {
            dao.deleteById(id);
            List<Long> idList = new ArrayList<>();
            idList.add(id);
            RxBus.get().post(RxBusEventType.Recent.DELETE_RECENT_MUSIC, RxbusListObject.instance(idList));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
